package com.sandman.article.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sandman.article.mapper.ArticleMapper;
import com.sandman.article.po.ArticlePo;
import com.sandman.article.service.ArticleService;
import com.sandman.constant.SortByConstant;
import com.sandman.vo.ArticleVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.sandman.constant.DateTimeFormatterConstant.DATE_TIME_FORMATTER;


/**
 * @author 范珈诚
 * time 10:33 PM 9/25/22
 * notes
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ArticlePo> implements ArticleService {

    private final ArticleMapper articleMapper;

    private final Logger logger = LoggerFactory.getLogger(ArticleServiceImpl.class);

    @Autowired
    public ArticleServiceImpl(ArticleMapper articleMapper) {
        this.articleMapper = articleMapper;
    }

    @Override
    public ArticleVo getOne(Byte sortBy) {
        //虽然可以用一个sql语句写完, 但是分成四份mapper写, 有助于拓展
        logger.info("获取文章根据:{}", sortBy);
        ArticlePo po;
        switch (sortBy) {
            case SortByConstant.NEWEST:
                po = articleMapper.getNewest();
                break;
            case SortByConstant.HOTTEST_24H:
                po = articleMapper.getHottest24H();
                break;
            case SortByConstant.HOTTEST_WEEK:
                po = articleMapper.getHottestWeek();
                break;
            case SortByConstant.RANDOM:
                po = articleMapper.getRandom();
                break;
            default:
                po = articleMapper.getNewest();
                break;
        }
        if (po == null) {
            //为空
            logger.info("返回了空文章");
            return null;
        }
        ArticleVo vo = new ArticleVo();
        BeanUtils.copyProperties(po, vo, "insertTime");
        vo.setInsertTime(po.getInsertTime().format(DATE_TIME_FORMATTER));
        logger.info("本次返回文章: {}", vo);
        return vo;
    }

    @Override
    public void createArticle(ArticleVo articleVo) {
        final String nickName = articleVo.getNickName();
        final String title = articleVo.getTitle();
        final String text = articleVo.getText();
        logger.info("新树洞入库, 化名:{},标题:{},正文:{}", nickName, title, text);
        ArticlePo newPo = new ArticlePo();
        newPo.setNickName(nickName);
        newPo.setTitle(title);
        newPo.setText(text);
        //todo
        newPo.setAuthor(1234);
        newPo.setLikeCount(0);
        newPo.setDislikeCount(0);
        newPo.setGeoIp("湖北武汉");
        newPo.setStatus((byte) 1);
        articleMapper.insert(newPo);
    }
}
